package com.icloud.article.boot.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.icloud.article.boot.dto.DiscussAttachmentDto;
import com.icloud.article.boot.mapper.DiscussAttachmentMapper;
import com.icloud.article.boot.model.DiscussAttachment;
import com.icloud.article.boot.service.DiscussAttachmentService;
import com.icloud.common.database.enums.DeleteEnum;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 评论附件service 实现类
 */

@Service
public class DiscussAttachmentServiceImpl extends ServiceImpl<DiscussAttachmentMapper, DiscussAttachment> implements DiscussAttachmentService {
    /**
     * 批量添加
     * @param discussId 评论id
     * @param dtoList 附件
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void batchAdd(Long discussId, List<DiscussAttachmentDto> dtoList) {
        //帖子没有附件，直接返回
        if(CollectionUtil.isEmpty(dtoList)){
            return;
        }

        //删除老附件数据
        update(new LambdaUpdateWrapper<DiscussAttachment>()
                .set(DiscussAttachment::getIsDelete, DeleteEnum.DELETED.getCode())
                .eq(DiscussAttachment::getDiscussId, discussId));

        //保存帖子附件
        List<DiscussAttachment> attachments = new ArrayList<>();
        for (DiscussAttachmentDto attachmentDto : dtoList) {
            DiscussAttachment attachment = new DiscussAttachment();
            BeanUtil.copyProperties(attachmentDto,attachment);
            attachment.setDiscussId(discussId);
            attachments.add(attachment);
        }
        saveBatch(attachments);
    }

    /**
     * 根据帖子id查询附件
     * @param discussIds 帖子ids
     * @return key:帖子id  value:附件列表
     */
    @Override
    public Map<Long, List<DiscussAttachment>> queryAttachmentCountByDisscuss(List<Long> discussIds) {
        List<DiscussAttachment> attachmentList = list(new LambdaQueryWrapper<DiscussAttachment>().in(DiscussAttachment::getDiscussId, discussIds));
        if(CollectionUtil.isEmpty(attachmentList)){
            return new HashMap<>();
        }

        return attachmentList.stream().collect(Collectors.groupingBy(DiscussAttachment::getDiscussId, Collectors.toList()));
    }
}
